"""
Flask后端服务
提供Fast-SCL仿真API
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import json
import threading
import time

from polar_code import PolarCode

app = Flask(__name__)
CORS(app)

# 全局变量存储仿真状态
simulation_status = {
    'running': False,
    'progress': 0,
    'results': None,
    'error': None
}

@app.route('/api/simulate', methods=['POST'])
def simulate():
    """开始仿真"""
    global simulation_status
    
    if simulation_status['running']:
        return jsonify({'error': '仿真已在进行中'}), 400
    
    try:
        data = request.json
        N = int(data.get('N', 1024))
        K = int(data.get('K', 512))
        L = int(data.get('L', 8))
        snr_start = float(data.get('snr_start', 0))
        snr_end = float(data.get('snr_end', 4))
        snr_step = float(data.get('snr_step', 0.5))
        num_trials = int(data.get('num_trials', 100))
        
        # 参数验证
        if N <= 0 or K <= 0 or K >= N:
            return jsonify({'error': '参数错误：N和K必须为正整数，且K < N'}), 400
        
        if L <= 0:
            return jsonify({'error': '参数错误：L必须为正整数'}), 400
        
        # 启动仿真线程
        simulation_status = {
            'running': True,
            'progress': 0,
            'results': None,
            'error': None
        }
        
        thread = threading.Thread(
            target=run_simulation,
            args=(N, K, L, snr_start, snr_end, snr_step, num_trials)
        )
        thread.start()
        
        return jsonify({'message': '仿真已启动'}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/status', methods=['GET'])
def get_status():
    """获取仿真状态"""
    return jsonify(simulation_status)

@app.route('/api/stop', methods=['POST'])
def stop_simulation():
    """停止仿真"""
    global simulation_status
    simulation_status['running'] = False
    return jsonify({'message': '仿真已停止'})

def run_simulation(N, K, L, snr_start, snr_end, snr_step, num_trials):
    """运行仿真"""
    global simulation_status
    
    try:
        # 创建极化码实例
        polar = PolarCode(N, K, L)
        
        # 生成SNR范围
        snr_range = np.arange(snr_start, snr_end + snr_step, snr_step)
        
        # 存储结果
        results = {
            'snr_db': snr_range.tolist(),
            'ber': [],
            'fer': []  # 帧错误率
        }
        
        total_points = len(snr_range)
        
        for i, snr_db in enumerate(snr_range):
            if not simulation_status['running']:
                break
                
            # 运行仿真
            ber = polar.simulate_ber([snr_db], num_trials)[0]
            results['ber'].append(ber)
            
            # 更新进度
            simulation_status['progress'] = int((i + 1) / total_points * 100)
            
            # 添加延迟避免阻塞
            time.sleep(0.1)
        
        if simulation_status['running']:
            simulation_status['results'] = results
            simulation_status['running'] = False
            
    except Exception as e:
        simulation_status['error'] = str(e)
        simulation_status['running'] = False

@app.route('/api/test', methods=['GET'])
def test():
    """测试API"""
    return jsonify({'message': 'Fast-SCL仿真服务运行正常'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
